import { createRouter, createWebHistory } from 'vue-router'
import RouterMenuEnum from '@/enums/routerMenuEnum'
import { useRouterMenu } from '@/stores/routerMenu'
import { useAccount } from '@/stores/account'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/index/survey'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/index',
      name: 'index',
      meta: {
        isAuth: true,
        ...RouterMenuEnum.INDEX
      },
      redirect: '/index/survey',
      component: () => import('../views/LayoutView.vue'),
      children: [
        {
          path: '/index/survey',
          name: 'survey',
          component: () => import('../views/SurveyView.vue')
        }
      ]
    },
    {
      path: '/running-monitor',
      name: 'runningMonitor',
      meta: {
        isAuth: true,
        ...RouterMenuEnum.RUNNING_MONITOR
      },
      redirect: '/running-monitor/city-power-monitor',
      component: () => import('../views/LayoutView.vue'),
      children: [
        {
          path: '/running-monitor/city-power-monitor',
          name: 'city-power-monitor',
          component: () => import('../views/CityPowerMonitorView.vue')
        },
        {
          path: '/running-monitor/photovoltaic-monitor',
          name: 'photovoltaic-monitor',
          component: () => import('../views/PhotovoltaicMonitorView.vue')
        }
      ]
    },
    {
      path: '/overview',
      name: 'overview',
      meta: {
        isAuth: true
      },
      component: () => import('../views/OverviewView.vue')
    },
    // 404
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('../views/NotFoundView.vue')
    }
  ]
})

/**
 * 全局路由前置守卫
 */
router.beforeEach((to, from, next) => {
  const routerMenuStore = useRouterMenu()
  const accountStore = useAccount()
  routerMenuStore.current = to.meta
  if (to.meta.isAuth) {
    //判断是否需要鉴权
    if (accountStore.isLogin) {
      next()
    } else {
      next({ name: 'login' })
    }
  } else {
    next()
  }
})

/**
 * 全局后置路由
 */
router.afterEach(() => {
  // ...
})

export default router
